package org.androidpn.server.xmpp.handler;

import org.androidpn.server.model.ChatMessage;
import org.androidpn.server.model.User;
import org.androidpn.server.service.ChatMsgService;
import org.androidpn.server.service.ServiceLocator;
import org.androidpn.server.service.UserNotFoundException;
import org.androidpn.server.service.UserService;
import org.androidpn.server.xmpp.UnauthorizedException;
import org.androidpn.server.xmpp.session.ClientSession;
import org.androidpn.server.xmpp.session.Session;
import org.androidpn.server.xmpp.session.SessionManager;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.QName;
import org.xmpp.packet.IQ;
import org.xmpp.packet.PacketError;

import java.util.Random;
import java.util.UUID;

/**
 * Created by huang on 2017/4/19 0019.
 */
public class IQChatMsgHandler extends IQHandler {
    private static final String NAMESPACE = "androidpn:iq:chatmsg";

    private SessionManager sessionManager;

    private ChatMsgService chatMsgService;

    private UserService userService;

    public IQChatMsgHandler() {
        this.sessionManager = SessionManager.getInstance();
        this.chatMsgService = ServiceLocator.getChatMsgService();
        this.userService = ServiceLocator.getUserService();
    }

    public IQ handleIQ(IQ packet) throws UnauthorizedException {
        IQ reply = null;

        ClientSession session = sessionManager.getSession(packet.getFrom());
        if (session == null) {
            log.error("Session not found for key " + packet.getFrom());
            reply = IQ.createResultIQ(packet);
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(PacketError.Condition.internal_server_error);
            return reply;
        }
        if (session.getStatus() == Session.STATUS_AUTHENTICATED) {
            if (IQ.Type.set.equals(packet.getType())) {
                Element element = packet.getChildElement();
                String toUserId = element.elementText("chatto");
                String fromUserId = element.elementText("chatfrom");
                String chatDate = element.elementText("chatdate");
                String message = element.elementText("message");
                String chatType = element.elementText("msgtype");

                System.out.println("IQChatMsg:\n" + "ToUser:" + toUserId +
                        "\nFromUser:" + fromUserId +
                        "\nDate:" + chatDate +
                        "\nMessage:" + message +
                        "\nType:" + chatType);
                User user = null;
                try {
                    user = userService.getUserByUsername(toUserId);
                } catch (UserNotFoundException e) {
                    e.printStackTrace();
                }
                if(user != null) {
                    Random random = new Random();
                    String uuid = UUID.randomUUID().toString();
                    ChatMessage chatMsg = new ChatMessage();
                    chatMsg.setToUser(toUserId);
                    chatMsg.setFromUser(fromUserId);
                    chatMsg.setMsgDate(chatDate);
                    chatMsg.setMessage(message);
                    boolean resultType = true;
                    if(Boolean.parseBoolean(chatType)) {
                        chatMsg.setMsgType(false);
                        resultType = false;
                    }else {
                        chatMsg.setMsgType(true);
                        resultType = true;
                    }
                    chatMsg.setUuid(uuid);
                    chatMsgService.saveChatMessage(chatMsg);

                    ClientSession tosession = sessionManager.getSession(toUserId);
                    if (tosession != null) {
                        if (tosession.getPresence().isAvailable()) {
                            IQ chatMsgIQ = createChatMsgIQ(toUserId,fromUserId,chatDate,message,Boolean.toString(resultType),uuid);
                            chatMsgIQ.setTo(tosession.getAddress());
                            tosession.deliver(chatMsgIQ);
                        }
                    }
                }

            }
        }
        return null;
    }

    public String getNamespace() {
        return NAMESPACE;
    }

    private IQ createChatMsgIQ(String toUserName, String fromuser, String date, String message, String msgtype, String uuid) {
        Element chatmsg = DocumentHelper.createElement(QName.get(
                "chatmsg", NAMESPACE));
        chatmsg.addElement("chatto").setText(toUserName);
        chatmsg.addElement("chatfrom").setText(fromuser);
        chatmsg.addElement("chatdate").setText(date);
        chatmsg.addElement("message").setText(message);
        chatmsg.addElement("msgtype").setText(msgtype);
        chatmsg.addElement("uuid").setText(uuid);
        IQ iq = new IQ();
        iq.setType(IQ.Type.set);
        iq.setChildElement(chatmsg);
        return iq;
    }
}
